<?php
class User extends AppModel {
 
    var $name = 'User'; 
    
    //var $order = 'Content.lft ASC';
    
    var $belongsTo = array('Group');

    /**
     * Provides automated functioning from Acl Behavior, which
     * in turn provides functionality from TreeBehavior
     * @access public
     * @var array
     */
	var $actsAs = array('Acl'=>'requester');
    //var $actsAs = array('Tree', 'Sluggable' => array('label' => 'page_url', 'overwrite' => true)); 
	
	var $validate = array(
    	'username' => array(
	    	'ruleName' => array(
	            'rule' => array('custom', '/^[a-z0-9.&()]*$/i'),
	    		'allowEmpty' => false,
	    		'message' => 'Username cannot be empty or use special characters'
	        ),
	        'ruleName2' => array(
	            'rule' => 'isUnique',
        		'message' => 'This username has already been taken.'
	        )
    	),
    	'password' => array(
	        'rule' => array('minLength', 8),
        	'message' => 'Password must contain at least 8 characters.'
	    )
    	
    );
    
    function parentNode(){
	    if (!$this->id) {
		    return null;
		}

		$data = $this->read();

		if (!$data['User']['group_id']){
		    return null;
		} else {
		    return array('model' => 'Group', 'foreign_key' => $data['User']['group_id']);
		}
    }

	function afterSave($created = null){
	    if( $created ){
		    $this->id = $this->getLastInsertId();
		    // first create alias for the newly created Aro
		    // ACL Behavior does NOT manage alias values
		    $this->__createAroAlias();
		} else {
            if( isset($this->data['User']['group_id']) && isset( $this->data['User']['old_group_id'] ) ){
				$this->__updateAclGroup();
			}
		}
	}

    /**
     * When the group_id has changed, then need to also change the parent_id field in the
	 * matching Aro row.
	 *
	 * @access private
     */
    function __updateAclGroup(){
	    if( $this->data['User']['group_id'] !== $this->data['User']['old_group_id'] ){
			// what is the id of the aro row that has $this->data['User']['group_id'] as it's foreign_key?
			$groupInfo = $this->Aro->find(array('foreign_key'=>$this->data['User']['group_id'], 'model'=>'Group') );
			$userAro = $this->Aro->find(array('foreign_key'=>$this->data['User']['id'], 'model'=>'User') );
			$updatedAro = array(
			    'Aro' => array(
				    'id' => $userAro['Aro']['id'],
					'parent_id' => $groupInfo['Aro']['id']
					)
				);
			$this->Aro->save( $updatedAro );
		}
	}


    /**
     * Creates an alias value for a newly created user.
     * 
	 * @returns boolean TRUE if alias value successfully changed.
     */
	function __createAroAlias()
	{
	    $aroId = $this->Aro->getLastInsertId();
		$this->Aro->create();
		$this->Aro->id = $aroId;
		if( $this->Aro->saveField('alias', $this->data['User']['username'] ) ){
		    return TRUE;
		} else {
		    return FALSE;
		}
	}

       
    
} 
?>